/*
 * @Author: songtao
 * @Date: 2021-11-17 16:33:50
 * @LastEditTime: 2021-11-22 19:08:49
 * @FilePath: \vue-cars\vue-admin\src\store\modules\app.js
 */
import {Login} from "@/api/login.js"
import { setToken , setUserName , getUserName , removeToken , removeUserName } from "../../utils/app";

const state = {
  isCollapse: JSON.parse(sessionStorage.getItem("isCollapse")) || false,
  token:"",
  username: getUserName() || '',
}

const mutations = {
  SET_ISCOLLAPSE: function(state){
    state.isCollapse = !state.isCollapse
    // 存储到本地
    sessionStorage.setItem("isCollapse", JSON.stringify(state.isCollapse))
  },
  SET_TOKEN(state,value){
    state.token = value
  },
  SET_USERNAME(state,value){
    state.username = value
  }
}

const actions = {
  login(content , data){
    return new Promise((resolve,reject) => {
      // 接口
      Login(data).then((res) => {
        let data = res.data.data
        if(res.data.resCode === 0){
          content.commit("SET_TOKEN", data.token)
          content.commit("SET_USERNAME", data.username)
          setToken(data.token)
          setUserName(data.username)
        }
        resolve(res)
      }).catch((err) => {
        reject(err)
      })
    })
  },
  exit({commit}){
    new Promise((resolve,reject) => {
      removeToken()
      removeUserName()
      commit("SET_TOKEN", "")
      commit("SET_USERNAME", "")
      resolve()
    })
    
  }
}

export default {
  namespaced:true,
  state,
  mutations,
  actions
};